﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Models;
using ChinaDynastyTours.Helpers;
using System.Configuration;
using System.Threading;
using DevExpress.XtraEditors;

namespace ChinaDynastyTours.Views
{
    public partial class VehicleOrderForm : DevExpress.XtraEditors.XtraForm
    {
        //输入参数
        public string _TourGroupID { get; set; }//团ID
        public string _LocalPlanScheduleDate { get; set; }//团状态
        public string _LocalPlanScheduleID { get; set; }//行程计划ID
        public string _TourGroupScheduleID { get; set; }//大程计划ID

        public int _AdultNum { get; set; }
        public int _ChildNum { get; set; }
        public string _HotelName { get; set; }
        public string _ArrivalFlight { get; set; }
        public string _ArrivalTime { get; set; }
        public string _LeaveFlight { get; set; }
        public string _LeaveTime { get; set; }

        public DataTable _dtOrderData;

        public string _CiceroniName { get; set; }
        public string _CiceroniPhone { get; set; }
        
        public VehicleOrderForm()//string tourGroupId, string localPlanScheduleDate, string localPlanScheduleId, string tourGroupScheduleId,int adultNum)
        {
            InitializeComponent();
        }
        
        private void VehicleOrderForm_Load(object sender, EventArgs e)
        {
            vehicleProviderGridControl.DataSource = ServiceInfoCtrl.GetVhicleServiceData();

            LoadSelectedPageGridViewData();
        }

        private void LoadSelectedPageGridViewData()
        {
            _dtOrderData = VehicleOrderCtrl.GetVehicleOrderData(_TourGroupID, _LocalPlanScheduleID);
            _dtOrderData.ColumnChanged += new DataColumnChangeEventHandler(OrderData_ColumnChanged);
            orderGridControl.DataSource = _dtOrderData;
        }

        #region 修改预订信息后的自动保存

        void OrderData_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            int providerId = int.Parse(e.Row["ProviderID"].ToString());
            string providerName = e.Row["ProviderName"].ToString();
            string serverName = e.Row["ServiceName"].ToString();

            VehicleOrderEntity vehicleOrder = new VehicleOrderEntity();

            vehicleOrder.VehicleOrderID = int.Parse(e.Row["VehicleOrderID"].ToString());/*重点字段*/
            vehicleOrder.ExpenseID = int.Parse(e.Row["ExpenseID"].ToString());

            vehicleOrder.OrderState = e.Row["OrderState"].ToString();/*重点内容，初始化订单状态为‘未定’*/
            vehicleOrder.TourgroupID = _TourGroupID;
            vehicleOrder.TourgroupName = TeamGroupCtrl.GetTeamGroupNameById(_TourGroupID);

            vehicleOrder.ProviderID = providerId;
            vehicleOrder.ProviderName = providerName;

            vehicleOrder.LocalPlanScheduleID = int.Parse(_LocalPlanScheduleID);
            vehicleOrder.ServiceDate = DateTime.Parse(e.Row["ServiceDate"].ToString()).ToString("yyyy-MM-dd");
            vehicleOrder.GuestNum = int.Parse(e.Row["GuestNum"].ToString()); //变更字段
            vehicleOrder.ArrivalFlight = e.Row["ArrivalFlight"].ToString();
            vehicleOrder.ArrivalTime = e.Row["ArrivalTime"].ToString();
            vehicleOrder.LeaveFlight = e.Row["LeaveFlight"].ToString();
            vehicleOrder.LeaveTime = e.Row["LeaveTime"].ToString();
            vehicleOrder.Hotel = e.Row["Hotel"].ToString();
            vehicleOrder.VehicleNum = int.Parse(e.Row["VehicleNum"].ToString()); //变更字段
            vehicleOrder.SinglePrice = decimal.Parse(e.Row["SinglePrice"].ToString());//变更字段
            vehicleOrder.CiceroniName = e.Row["CiceroniName"].ToString();
            vehicleOrder.VehicleType = e.Row["VehicleType"].ToString();
            vehicleOrder.ServiceName = serverName;
            vehicleOrder.ContractPath = e.Row["ContractPath"].ToString();
            vehicleOrder.Remark = e.Row["Remark"].ToString();//变更字段


            ExpenseEntity expense = new ExpenseEntity()
            {
                /*这里只有Budget在界面中是可被修改的内容，其余全部用原值更新*/
                ExpenseID = int.Parse(e.Row["ExpenseID"].ToString()), /*重点字段*/
                ProviderID = providerId,
                ProviderName = providerName,
                ServiceName = serverName,

                //Budget = decimal.Parse(e.Row["Budget"].ToString()),
                Budget = decimal.Parse(e.Row["SinglePrice"].ToString()) * int.Parse(e.Row["VehicleNum"].ToString()),
                TourgroupID = e.Row["TourgroupID"].ToString(),
                Remark = e.Row["Remark"].ToString(),
                Status = e.Row["Status"].ToString(),
                TypeBelong = e.Row["TypeBelong"].ToString(),
            };

            VehicleOrderCtrl.UpdateVehicleOrderData(expense, vehicleOrder);

            //更新团审核成本
            TeamGroupCtrl.UpdateTourGroupBudgeCost(_TourGroupID);

            //刷新页面，此处刷新页面会导致选择供应商出现问题，暂不刷新
            //LoadSelectedPageGridViewData();



        }
        #endregion
        
        private void CreateVehicleOrderData(DevExpress.XtraGrid.Views.Grid.GridView gridView,DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            string serverName = vehicleProviderGridView.GetRowCellValue(e.RowHandle, "ServiceName").ToString();
            //int providerId = int.Parse(vehicleProviderGridView.GetRowCellValue(e.RowHandle, "ProviderID").ToString());
            //string providerName = vehicleProviderGridView.GetRowCellValue(e.RowHandle, "ProviderName").ToString();


            //创建汽车预定信息内容
            VehicleOrderEntity vehicleOrder = new VehicleOrderEntity();
            vehicleOrder.OrderState = OrderStateEnum.未订.ToString();/*重点内容，初始化订单状态为‘未定’*/
            vehicleOrder.TourgroupID = _TourGroupID;
            vehicleOrder.TourgroupName = TeamGroupCtrl.GetTeamGroupNameById(_TourGroupID);
            
            vehicleOrder.ProviderID = -1;
            vehicleOrder.ProviderName = "";

            vehicleOrder.LocalPlanScheduleID = int.Parse(_LocalPlanScheduleID);
            vehicleOrder.ServiceDate = DateTime.Parse(_LocalPlanScheduleDate).ToString("yyyy-MM-dd");
            vehicleOrder.GuestNum = _AdultNum + _ChildNum;
            vehicleOrder.ArrivalFlight = _ArrivalFlight;
            vehicleOrder.ArrivalTime = _ArrivalTime;
            vehicleOrder.LeaveFlight = _LeaveFlight;
            vehicleOrder.LeaveTime = _LeaveTime;
            vehicleOrder.Hotel = _HotelName;
            vehicleOrder.VehicleNum = 1;
            vehicleOrder.SinglePrice = decimal.Parse(vehicleProviderGridView.GetRowCellValue(e.RowHandle, "Price").ToString());
            vehicleOrder.CiceroniName = _CiceroniName;//TeamGroupCtrl.GetTourGroupScheduleAccompanyNames(_TourGroupID);
            vehicleOrder.VehicleType = vehicleProviderGridView.GetRowCellValue(e.RowHandle, "VehicleType").ToString();
            vehicleOrder.ServiceName = serverName;
            vehicleOrder.ContractPath = "";
            vehicleOrder.Remark = "";
            //vehicleOrder.PriceType = VehiclePriceType.按人.ToString();
            //vehicleOrder.KilometerNum = 0;
            //vehicleOrder.JourneyType = VehicleJourneyType.单程.ToString();


            //创建费用
            ExpenseEntity expense = new ExpenseEntity()
            {
                //ExpenseID = _ExpenseID,
                TourgroupID = _TourGroupID,
                TourgroupName=TeamGroupCtrl.GetTeamGroupNameById(_TourGroupID),
                TourGroupScheduleID = int.Parse(_TourGroupScheduleID),
                ProviderID = -1,
                ProviderName = "",
                ServiceName = serverName,
                Budget = decimal.Parse(vehicleProviderGridView.GetRowCellValue(e.RowHandle, "Price").ToString()),
                PayTotal = 0,
                ApplyPayTotal = 0,
                AdjustAmount = 0,
                Status = ExpenseStatusEnum.计划.ToString(),
                TypeBelong = ProviderTypeEnum.汽车.ToString(),
                ApplyPay = 0,
                PayStatus = PayApplyStatusEnum.未付.ToString(),
                CreateByUserName = Thread.CurrentPrincipal.Identity.Name, //UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name)
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd"),
                ExpenseTypeID = 4,//所属费用类型(费用类型表中存储着编号，此编号是固定的，1房费、2团费、3餐费、4交通费、5门票、6杂费)
                ExpenseType = BaseInfoCtrl.GetExpenseTypeNameByID(4)//同上
            };
            VehicleOrderCtrl.CreateVehicleOrderAndExpenseData(expense, vehicleOrder);
            
            //更新团审核成本
            TeamGroupCtrl.UpdateTourGroupBudgeCost(_TourGroupID);
        }


        private void ProviderGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.Clicks == 2)
            {
                CreateVehicleOrderData(sender as DevExpress.XtraGrid.Views.Grid.GridView, e);
            }
            //刷新数据
            LoadSelectedPageGridViewData();
            //orderGridControl.DataSource = VehicleOrderCtrl.GetVehicleOrderData(_TourGroupID, _LocalPlanScheduleID);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
             ProviderGridView_RowClick(vehicleProviderGridView, new DevExpress.XtraGrid.Views.Grid.RowClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 2, 0, 0, 0), vehicleProviderGridView.FocusedRowHandle));
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "Status").ToString() != ExpenseStatusEnum.计划.ToString()
                || orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "PayStatus").ToString() != PayApplyStatusEnum.未付.ToString()
                || orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "OrderState").ToString() != OrderStateEnum.未订.ToString())
            {
                MessageBox.Show("该预订已生效，不能删除！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            
            VehicleOrderCtrl.DeleteVehicleOrder(
                    orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "VehicleOrderID").ToString(),
                    orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "ExpenseID").ToString());
            
            //更新团审核成本
            TeamGroupCtrl.UpdateTourGroupBudgeCost(_TourGroupID);

            //刷新数据
            LoadSelectedPageGridViewData();
            //orderGridControl.DataSource = VehicleOrderCtrl.GetVehicleOrderData(_TourGroupID, _LocalPlanScheduleID);
        }

        private void ProviderNameEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ButtonEdit btnEdit = sender as ButtonEdit;

            ProviderSelectedToolForm providerForm = new ProviderSelectedToolForm();
            providerForm._ProviderTypes = new ProviderTypeEnum[] { ProviderTypeEnum.汽车 };
            //providerForm._ProviderName = orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "ProviderName").ToString();

            if (providerForm.ShowDialog(this) == DialogResult.OK)
            {
                btnEdit.EditValue = providerForm.ReturnProviderName;
                orderGridView.SetRowCellValue(orderGridView.FocusedRowHandle, "ProviderID", providerForm.ReturnProviderID);
                orderGridView.SetRowCellValue(orderGridView.FocusedRowHandle, "ProviderName", providerForm.ReturnProviderName);
            }

        }

        #region 关闭窗口保存数据
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void VehicleOrderForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //激发团数据更新,转移一下焦点即可
            btnExit.Focus();
        } 
        #endregion

    }
}
